//
//  WXTableViewViewController.m
//  WXUIKit
//
//  Created by Daly Dai on 12-7-14.
//  Copyright (c) 2012年 baidu. All rights reserved.
//
#import "LVBaseTableView.h"
#import "UIColor-Expanded.h"
#import "GloableEngineService.h"
#import "BWXUIKit.h"

#define TableViewFrameWithoutKeyboard CGRectMake(0, 0, 320,IsIphone5?368+88:368)
#define TableViewFrameWithKeyboard    CGRectMake(0, 0, 320, IsIphone5?200+88:200)



@interface LVBaseTableView ()
{
	NSString *loadingUpText, *loadingReleaseText, *loadingText;
	MBProgressHUD *HUD;
    NSDate *_lastDate;
}
@property (nonatomic,retain) NSDate *lastDate;
@end

@implementation LVBaseTableView
@synthesize waitingLoadDataView;
@synthesize lastDate=_lastDate;
@synthesize parentViewController=_parentViewController;
@synthesize baseTableView = _baseTableView;
@synthesize refreshFooterView = _refreshFooterView;

- (id)init
{
    self = [super init];
    if (self) {
        _lastDate = nil;
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self loadView];
    }
    return self;
}

- (void)initTableView {
	_baseTableView = [[PullTableView alloc] initWithFrame:TableViewFrameWithoutKeyboard style:UITableViewStylePlain includeRefreshView:NO includeLoadMoreView:NO];
	_baseTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	_baseTableView.delegate = self;
	_baseTableView.dataSource = self;
    _baseTableView.pullDelegate = self;
	_baseTableView.backgroundColor = [UIColor clearColor];
    _baseTableView.pullTextColor = [UIColor redColor];
}

- (void)showLoading
{
    if (!self.waitingLoadDataView) {
        [self bringSubviewToFront:HUD];
        [HUD show:YES];
    } else {
        self.waitingLoadDataView.hidden = NO;
    }
}

- (void)hiddenLoading
{
    isLoading = NO;
    if (!self.waitingLoadDataView) {
        [HUD hide:YES];
    } else {
        self.waitingLoadDataView.hidden = YES;
    }
}



- (void)loadView
{
    HUD = [[[MBProgressHUD alloc] initWithView:self] autorelease];
    HUD.labelText = @"加载中...";
    [self addSubview:HUD];
    
	if (!_baseTableView) {
		[self initTableView];
	}

	[self addSubview:_baseTableView];
}


- (void)dealloc
{
    _baseTableView.dataSource = nil;
    _baseTableView.delegate = nil;
    _baseTableView.pullDelegate = nil;
    [self removeFooterView];
    [refreshHeaderView removeFromSuperview];
    refreshHeaderView = nil;
    _baseTableView.tableHeaderView = nil;
    
    self.baseTableView = nil;
    
//    [_baseTableView release];
//    _baseTableView = nil;
    HUD = nil;
    [super dealloc];
}

#pragma mark EGO
- (void)addPullRefresh
{
    //当tableView是pullTableView，自带下拉刷新
    if ([_baseTableView isKindOfClass:[PullTableView class]]) {
        _baseTableView.includeRefreshView = YES;
        return;
    }
	CGRect rect = CGRectMake(0,0, _baseTableView.frame.size.width, 0);
    if (!refreshHeaderView) {
        refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:rect];
        refreshHeaderView.delegate = self;
        refreshHeaderView.downText = @"下拉可更新";
        refreshHeaderView.releaseText = @"松开即可加载";
        refreshHeaderView.loadingText = @"正在载入…";
    }
	
	if (![refreshHeaderView superview]) {		
		//[_baseTableView addSubview:refreshHeaderView];
        _baseTableView.tableHeaderView = refreshHeaderView;
	}
	//refreshHeaderView.frame = rect;
}

- (void)addPullLoadMore {
    //当tableView是pullTableView，自带上拉加载更多
    if ([_baseTableView isKindOfClass:[PullTableView class]]) {
        _baseTableView.includeLoadMoreView = YES;
        return;
    }
	CGRect rect = CGRectMake(0, 0, _baseTableView.frame.size.width, 40);
	if (isPullLoadMore) {	// Load More View
		if (refreshFooterView == nil) {
			refreshFooterView = [[EGORefreshTableFooterView alloc] initWithFrame:rect];
			refreshFooterView.delegate = self;
			refreshFooterView.upText = loadingUpText ? loadingUpText : @"上拉展示更多";
			refreshFooterView.releaseText = loadingReleaseText ? loadingReleaseText : @"松开载入更多";
			refreshFooterView.loadingText = loadingText ? loadingText : @"正在载入…";
		}
	}
	
	// tableView在|viewDidUnload|中被释放后，需要重新添加
	if (![refreshFooterView superview]) {
		//[_baseTableView addSubview:refreshFooterView];
        _baseTableView.tableFooterView = refreshFooterView;
	}
    //refreshFooterView.frame = rect;
}

// 下拉/上拉操作数据获取完成后的处理
-(void)refreshDataPostHandler
{    
    [HUD hide:NO afterDelay:1.0];
    // ”下拉刷新/上拉载入更多“的处理
    [self performSelector:@selector(finishRefreshingData) withObject:self afterDelay:1];
    [self performSelector:@selector(finishLoadMoreData) withObject:self afterDelay:1];
    [_baseTableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	NSAssert(NO, @"Must be implemented by subclass");
    // Return the number of sections.
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	NSAssert(NO, @"Must be implemented by subclass");
    // Return the number of rows in the section.
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    
    return cell;
}



#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSAssert(NO, @"Must be implemented by subclass");
}


#pragma mark -
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //当tableView是pullTableView，自带实现
    if ([_baseTableView isKindOfClass:[PullTableView class]]) {
        return;
    }
    
	[refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
	
	if (isPullLoadMore) {
		[refreshFooterView egoRefreshScrollViewDidScroll:scrollView];
	}
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    //当tableView是pullTableView，自带实现
    if ([_baseTableView isKindOfClass:[PullTableView class]]) {
        return;
    }
    
	[refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
	if (isPullLoadMore) {
		[refreshFooterView egoRefreshScrollViewDidEndDragging:scrollView];
	}
}

#pragma mark -
#pragma mark pullTableViewDelegate
-(void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    [self loadMoreData];
}

-(void)pullTableViewDidTriggerRefresh:(PullTableView *)pullTableView
{
    [self refreshData];
}


#pragma mark -
#pragma mark EGORefreshTableFooterDelegate
- (void)egoRefreshTableFooterDidTriggerRefresh:(EGORefreshTableFooterView*)v{
	isLoading = YES;
	[self loadMoreData];
}

- (BOOL)egoRefreshTableFooterDataSourceIsLoading:(EGORefreshTableFooterView *)v {
	return isLoading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableFooterDataSourceLastUpdated:(EGORefreshTableFooterView *)v {
    if (![[GloableEngineService sharedInstance] networkOK] ) {
         if ( nil == self.lastDate )
             self.lastDate = [NSDate date];
         return self.lastDate;
    }
    self.lastDate = [NSDate date];
	return self.lastDate; // should return date data source was last changed
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)v {
	isLoading = YES;
	[self refreshData];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)v {
	return isLoading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)v {
    if (![[GloableEngineService sharedInstance] networkOK] ) {
        if ( nil == self.lastDate )
            self.lastDate = [NSDate date];
        return self.lastDate;
    }
    self.lastDate = [NSDate date];
	return self.lastDate; // should return date data source was last changed
}

#pragma mark -
#pragma mark showloadingView

//为了提高扩展性，删除原有requstDataList接口，子类必须实现loadMoreData和refreshData方法.
- (void)loadMoreData {
    
    if (!_baseTableView.pullDelegate)
    {
        NSAssert(NO, @"Must be implemented by subclass，为了保证扩展性，tableview需要子类必须实现loadMoreData和refreshData方法");
    }
}

- (void)refreshData
{
    if (!_baseTableView.pullDelegate)
    {
        NSAssert(NO, @"Must be implemented by subclass，为了保证扩展性，tableview需要子类必须实现loadMoreData和refreshData方法");
    }
}


- (void)finishLoadMoreData
{
    _baseTableView.pullTableIsLoadingMore = NO;
    [self hiddenLoading];	
	// Move the loading view Y position
	//CGRect frame = refreshFooterView.frame;
	//refreshFooterView.frame = CGRectMake(frame.origin.x, tableView.contentSize.height, frame.size.width, 40);
	[refreshFooterView egoRefreshScrollViewDataSourceDidFinishedLoading:_baseTableView];
}


- (void)finishRefreshingData 
{
    _baseTableView.pullTableIsRefreshing = NO;
    [self hiddenLoading];
	[refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_baseTableView];
	//refreshFooterView.frame = CGRectMake(0.0f, _baseTableView, _baseTableView.frame.size.width, _baseTableView.bounds.size.height);
}


- (void)removeFooterView
{
    [refreshFooterView removeFromSuperview];
    [refreshFooterView release];
    refreshFooterView = nil;
    _baseTableView.tableFooterView = nil;
}

- (void)noMoreData 
{
	isPullLoadMore = NO;
    [self performSelectorOnMainThread: @selector(removeFooterView) withObject: nil waitUntilDone: NO];
}


#pragma mark --
- (void)setTableHeaderView:(UIView*)headerView
{
    _baseTableView.tableHeaderView = headerView;
    CGRect rect = CGRectMake(0, _baseTableView.contentSize.height, _baseTableView.frame.size.width, _baseTableView.bounds.size.height);
	refreshFooterView.frame = rect;

}

@end
